package com.cskaoyan.service;

import com.cskaoyan.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

/**
 * @author stone
 * @date 2022/12/21 15:12
 */
@Service
public class AccountServiceImpl implements AccountService{
    @Autowired
    AccountMapper accountMapper;
    @Autowired
    PlatformTransactionManager transactionManager;

    @Override
    public int transfer(int fromId, int destId, int money) {
        // 开启事务 TransactionManager.getTransaction
        TransactionStatus transactionStatus = transactionManager.getTransaction(TransactionDefinition.withDefaults());
        try {
            originMethod(fromId, destId, money);// ctrl+alt+M
            // 事务的提交 TransactionManager.commit
            transactionManager.commit(transactionStatus);
        } catch (Exception exception) {
            // 事务的回滚
            transactionManager.rollback(transactionStatus);
            exception.printStackTrace();
        }
        return 0;
    }

    @Override
    public int modify(int id, int money) {

        TransactionStatus transactionStatus = transactionManager.getTransaction(TransactionDefinition.withDefaults());
        try {
            // 执行业务代码
            int i = accountMapper.updateMoney(id, money);
            // 事务的提交 TransactionManager.commit
            transactionManager.commit(transactionStatus);
        } catch (Exception exception) {
            // 事务的回滚
            transactionManager.rollback(transactionStatus);
            exception.printStackTrace();
        }
        return 0;
    }

    private void originMethod(int fromId, int destId, int money) {
        // 查询fromid的money并减去money = 转账后fromId应该有的money
        int fromMoney = accountMapper.selectMoney(fromId);// - money;
        int destMoney = accountMapper.selectMoney(destId);// + money;
        fromMoney -= money;
        destMoney += money;

        accountMapper.updateMoney(fromId, fromMoney);
        int i = 1 / 0;
        accountMapper.updateMoney(destId, destMoney);
    }
}
